package com.khotyn.heresy.service;

import java.util.Date;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.bean.PicComment;
import com.khotyn.heresy.bean.PictureDetail;
import com.khotyn.heresy.dao.KeywordDAO;
import com.khotyn.heresy.dao.PicCommentDAO;
import com.khotyn.heresy.dao.PictureDAO;
import com.khotyn.heresy.exception.IllegalServiceParamException;
import com.khotyn.heresy.util.KeywordFilter;

/**
 * Add comment service
 * 
 * @author khotyn
 * 
 */
public class AddCommentService {
	private PicCommentDAO picCommentDAO;
	private PictureDAO pictureDAO;
	private KeywordDAO keywordDAO;

	public PictureDetail doService(String pictureID, String commentContent, Integer userID) throws IllegalServiceParamException {
		commentContent = KeywordFilter.doFilter(commentContent, getKeywordDAO().selectAllKeywords());
		PicComment picComment = generatePicComment(pictureID, userID, commentContent);
		return doDBOperate(pictureID, picComment);
	}

	public PictureDetail doDBOperate(String pictureID, PicComment picComment) throws IllegalServiceParamException {
		picCommentDAO.insertPicComment(picComment);
		PictureDetail picture = pictureDAO.selectPicByPicID(pictureID);

		// The picture does not exists
		if (picture == null) {
			throw new IllegalServiceParamException(new HeresyErrorMessage("The picture you want to comment does not exists", "Operator Failed",
					"/Dragonfly"));
		}

		picture.setComments(picCommentDAO.selectPagedCommentByPicID(pictureID, 0, 10));

		return picture;
	}

	public PicComment generatePicComment(String pictureID, Integer userID, String commentContent) {
		PicComment picComment = new PicComment();
		picComment.getCommentUser().setUserID(userID);
		picComment.setPictureID(pictureID);
		picComment.setCommentContent(commentContent);
		picComment.setCommentTime(new Date(System.currentTimeMillis()));

		return picComment;
	}

	/**
	 * @return the picCommentDAO
	 */
	public PicCommentDAO getPicCommentDAO() {
		return picCommentDAO;
	}

	/**
	 * @param picCommentDAO the picCommentDAO to set
	 */
	public void setPicCommentDAO(PicCommentDAO picCommentDAO) {
		this.picCommentDAO = picCommentDAO;
	}

	/**
	 * @param pictureDAO the pictureDAO to set
	 */
	public void setPictureDAO(PictureDAO pictureDAO) {
		this.pictureDAO = pictureDAO;
	}

	/**
	 * @return the pictureDAO
	 */
	public PictureDAO getPictureDAO() {
		return pictureDAO;
	}

	/**
	 * @param keywordDAO the keywordDAO to set
	 */
	public void setKeywordDAO(KeywordDAO keywordDAO) {
		this.keywordDAO = keywordDAO;
	}

	/**
	 * @return the keywordDAO
	 */
	public KeywordDAO getKeywordDAO() {
		return keywordDAO;
	}
}
